package csa

import (
	"git.sr.ht/~mil/mobroute/src/db"
)

// TransferPossibleBetweenConnections determines whether a transfer is possible
// given two connections, the transfers map, and implicit/max transfer secs.
//
// There are a few cases to consider:
//
//  1. If the trip id are equal, it's the same trip in anycase, so this is
//     just an automatic true
//
//  2. If there is no from connection, this means this is the first time
//     we've seen the stop (e.g. from a walk), as well an auto true
//
//  3. If we know the transfer costs from a->b, essentially we just look
//     at time we got to a, delta the time for b and just ensure that
//     delta is greater then the **transfer cost** (e.g. defined from transfers)
//     AND delta is less then the max time we can take for a transfer total
//
//  4. Finally, implicit transfers (e.g. SIDUs equal) can take a passed transfer
//     cost wherein transfer not defined in map but this cost is used and logic
//     from (3) otherwise holds
func TransferPossibleBetweenConnections(
	transfersMap map[string]map[string]uint,
	fromConnection, toConnection *db.Connection,
	implicitTransferSeconds, maxTransferSeconds uint,
) bool {
	if fromConnection == nil {
		return false
	}

	var transferCost *uint = nil
	if t, transferCostKnownA := transfersMap[fromConnection.ToSSIDU]; transferCostKnownA {
		if cost, transferCostKnownB := t[toConnection.FromSSIDU]; transferCostKnownB {
			ccost := cost
			transferCost = &ccost
		}
	}
	if transferCost == nil && fromConnection.ToSSIDU == toConnection.FromSSIDU {
		transferCost = &implicitTransferSeconds
	}

	if transferCost == nil {
		return false
	} else {
		delta := toConnection.FromST - fromConnection.ToST
		return delta < maxTransferSeconds && delta > *transferCost
	}
}
